package org.cnbi.web.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cnbi.entity.IndicatorExpression;
import org.cnbi.entity.Kemu;
import org.cnbi.entity.Menu;
import org.cnbi.service.IComposeService;
import org.cnbi.utils.convert.OjbectConvertUtil;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.utils.pojo.indicator.IndicatorDimBean;
import org.cnbi.utils.pojo.indicator.IndicatorParams;
import org.cnbi.utils.pojo.kemu.KemuParams;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.MenuConstants;
import org.cnbi.utils.tools.StateConstants;
import org.cnbi.utils.tools.SymbolConstants;
import org.cnbi.web.controller.base.BaseController;
import org.cnbi.web.utils.ContextHolderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统请求页面的核心控制器 凡是是请求页面的动作，都到这里来写吧！ Copyright © 2014中国经邦. All rights reserved.
 * 
 * @author 龚佳新
 * @date 2014年4月17日下午12:47:04
 * @cnbi-web
 */
@Controller
@RequestMapping("/compose")
public class ComposeController extends BaseController {
	
	private static final Log logger = LogFactory.getLog(ComposeController.class);
	@Autowired
	private IComposeService composeService;

	@RequestMapping(value = "/index")
	public ModelAndView main(HttpServletResponse response) {
		ModelAndView view = firstNavHandle(MenuConstants.COMPOSE, response);
		compose(view);
		return view;
	}
	private void compose(ModelAndView view){
		List<Menu> list = new ArrayList<Menu>();
		list.add(new Menu("1","常用",MenuConstants.INDICATOR));
		list.add(new Menu("2","行业",MenuConstants.INDICATOR));
		view.addObject("listDatas", list);
		
	}
	
	private IndicatorExpression getIndicatorExpression(String arr[]){
		  int nid = Integer.parseInt(arr[1]);
		  List<IndicatorExpression> list = getIndicatorList();
		  for (IndicatorExpression bean :list){
			  if(bean.getId() == nid){
				  return bean;
			  }
		  }
		  return  null;
	}
	private Object indicator(ModelAndView view,Menu menu){
		  String arr[] =getDimHelpArr(menu.getScode());
		  String id = arr[1];
		  menu.setScode(arr[0]);
		  menu.setNote(id);
		  int nid = Integer.parseInt(arr[1]);
		  view.addObject("nid", nid);
		  IndicatorExpression bean = getIndicatorExpression(arr);
		  if(nid == 1){
			  StringBuffer sf = new StringBuffer();
			for (IndicatorExpression c : bean.getChildren()){
				if(null !=c.getChildren() && c.getChildren().size()>0){
					sf.append(c.getName()).append(SymbolConstants.COMMON);
				}
			}
			int len = sf.length();
			if(len>0)sf.delete(len-1, len);
		    view.addObject("letterArr", sf.toString().split("\\"+SymbolConstants.COMMON));
		  }
		return bean;
	}
	private Object kemu(ModelAndView view) {
		@SuppressWarnings("unchecked")
		List<Kemu> kemus = (List<Kemu>) ContextHolderUtils.getServletContext().getAttribute(MenuConstants.KEMU + MenuConstants.TREE + StateConstants.LIST);
		//logger.info(JsonUtil.generateJson(kemus));
		return kemus;
	}

	/**
	 * 响应二级菜单页面
	 * @param param
	 * @param menu
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/" + MenuConstants.LEVELTWO)
	public ModelAndView levelTwo(SqlParamsBean param, Menu menu, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = secondNavHandle(menu, response);
		Object object = null;
		if (menu.getScode().contains(MenuConstants.INDICATOR)){
			object = indicator(view,menu);
		}else if(menu.getScode().contains(MenuConstants.KEMU)){
			object = kemu(view);
			//int nlevel = composeService.queryKemuLevel(getSqlByKey(MenuConstants.KEMU+KemuConstants.NLEVEL));
			//view.addObject(KemuConstants.NLEVEL, nlevel);
		}
		view.addObject(Constants.DATAS, object);
		dimMapHandle(view, param, menu);
		return view;
	}
	private String getPeriodName(String period){
		period = period.substring(0, 4)+"年"+period.substring(4, 6)+"月";
		return period;
	}
	
	@RequestMapping(value = "/" + Constants.DATAS)
	public ModelAndView datas(IndicatorParams queryParam, Menu menu, HttpServletRequest request, HttpServletResponse response) {
		menu.setScode(MenuConstants.INDICATOR);
		long a = System.currentTimeMillis();
		//menu.getFavicon().length()
		ModelAndView view = secondNavHandle(menu, response);//indicatorperiod  //indicatorpoint
		List<IndicatorDimBean> list = OjbectConvertUtil.getIndicatorDimBeanList(getIndicatorMap(),queryParam);
		Map<String, String> sqlMap = getSqlMap();
		for (int i=0,len = list.size();i<len;i++){
			IndicatorDimBean bean = list.get(i);
			bean.setCompanyName(getCompany(bean.getCompany()).getSname());
			bean.setPeriodName(getPeriodName(bean.getPeriod()));
			IndicatorExpression datas = composeService.queryIndicatorList(sqlMap,bean);
			bean.setIndicatorBean(datas);
			//System.out.println(datas.getName()+bean.getCompanyName()+bean.getPeriodName()+"==="+datas.getDatas());
		}
		logger.info("查询个指标共历时："+(System.currentTimeMillis()-a)+"毫秒！");
		view.addObject(Constants.DATAS, list);
		view.addObject("queryParam", queryParam);
		return view;
	}
	
	
	@RequestMapping(value = "/" + MenuConstants.KEMU+Constants.DATAS)
	public ModelAndView kemuDatas(KemuParams queryParam,Menu menu,HttpServletResponse response){
		ModelAndView view = secondNavHandle(menu, response);
		String sql = "";
		//是否进行行列转置
		boolean flag = false;
		// 期间为 多期间 和 多期间 时 进行行列转置;
		if(queryParam.getPeriod().length < 2 || (queryParam.getPeriod().length >= 2 && queryParam.getKemu().length < 2)){
			sql = getSqlByKey(MenuConstants.KEMU+"notRanksOfRranspose");
			for (int i = 0; i < queryParam.getPeriod().length; i++) {
				if(queryParam.getPeriod().length == 1){
					view.addObject("period", getPeriodName(queryParam.getPeriod()[0]));
					view.addObject("helpDim", "period");
				}else{
					view.addObject("helpDim", "account");
				}
			}
		}else{
			view.addObject("helpDim", "rans");
			sql = getSqlByKey(MenuConstants.KEMU+"ranksOfRranspose");
			flag = true;
		}
		if(queryParam.getCompany().length < 2){
			view.addObject("company", getCompany(queryParam.getCompany()[0]));
		}
		Map map  = composeService.queryKemuList(sql,queryParam,flag);
		view.addObject(Constants.DATAS, map.get(Constants.DATAS));
		view.addObject("label", map.get("label"));
		//logger.info(JsonUtil.generateJson(map.get("label")));
		view.addObject("queryParam", queryParam);
		view.addObject("measure", (Map<String,String>) ContextHolderUtils.getServletContext().getAttribute(Constants.SUBJECT + GlobalConstants.SUBJECT_KEMU));
		return view;
	}
	

}

